

package com.maoshi.shop.distribution.api.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.maoshi.shop.bean.distribution.UserShoppingDataDto;
import com.maoshi.shop.common.config.Constant;
import com.maoshi.shop.common.exception.MaoshiShopBindException;
import com.maoshi.shop.common.util.IdUtil;
import com.maoshi.shop.common.util.Json;
import com.maoshi.shop.dao.OrderMapper;
import com.maoshi.shop.distribution.comment.model.DistributionAuditingSet;
import com.maoshi.shop.distribution.comment.model.DistributionRecruitSet;
import com.maoshi.shop.distribution.comment.model.DistributionUser;
import com.maoshi.shop.distribution.api.param.DistributionUserParam;
import com.maoshi.shop.distribution.comment.service.DistributionAuditingSetService;
import com.maoshi.shop.distribution.comment.service.DistributionRecruitSetService;
import com.maoshi.shop.distribution.comment.service.DistributionUserService;
import com.maoshi.shop.distribution.comment.vo.DistributionAuditingInfoVO;
import com.maoshi.shop.security.api.model.MaoshiUser;
import com.maoshi.shop.security.api.util.SecurityUtils;
import com.maoshi.shop.security.comment.enums.App;
import com.maoshi.shop.security.comment.model.AppConnect;
import com.maoshi.shop.security.comment.service.AppConnectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 分销邀请接口
 */
@Slf4j
@RestController
@RequestMapping("/p/distribution/register")
@Api(tags = "分销员注册接口")
@AllArgsConstructor
public class DistributionRegisterController {

    private final DistributionUserService distributionUserService;

    private final DistributionAuditingSetService distributionAuditingSetService;

    private final OrderMapper orderMapper;

    private final AppConnectService appConnectService;

    private final IdUtil idUtil;

    private final DistributionRecruitSetService distributionRecruitSetService;

    @GetMapping("/condition")
    @ApiOperation(value = "成为分销员所需要填写的信息")
    public ResponseEntity<DistributionAuditingInfoVO> getDistributionAuditingInfoVO(){
        DistributionAuditingSet distributionAuditingSet = distributionAuditingSetService.getByShopId();
        return ResponseEntity.ok(distributionAuditingSet.getAuditingInfo());
    }



    /**
     * 成为分销员
     */
    @PostMapping("/addDistributionUser")
    @ApiOperation(value = "申请成为分销员", notes = "申请成为分销员，返回分销员状态 0 待审核 1 正常")
    public ResponseEntity<Integer> addDistributionUser(@Valid @RequestBody DistributionUserParam distributionUserParam) {

        log.debug(Json.toJsonString(distributionUserParam));
        Long shopId = Constant.PLATFORM_SHOP_ID;
        DistributionRecruitSet distributionRecruitSet = distributionRecruitSetService.getByShopId();
        if (distributionRecruitSet.getState() == 0) {
            throw new MaoshiShopBindException("推广计划已关闭");
        }
        // 店铺分销员审核设置
        DistributionAuditingSet distributionAuditingSet = distributionAuditingSetService.getByShopId();
        //判断传入的资料是否齐全
        DistributionAuditingInfoVO distributionAuditingInfoVO =distributionAuditingSet.getAuditingInfo();
        if(distributionAuditingInfoVO == null){
            throw new MaoshiShopBindException("分销设置异常");
        }

        if(distributionAuditingInfoVO.getIdentityCardNumber()){
            if(!StrUtil.isNotBlank(distributionUserParam.getIdentityCardNumber())){
                throw new MaoshiShopBindException("申请填写信息不全,需要身份证号");
            }
        }
        if(distributionAuditingInfoVO.getIdentityCardPic()){
            if(!StrUtil.isNotBlank(distributionUserParam.getIdentityCardPicBack())||!StrUtil.isNotBlank(distributionUserParam.getIdentityCardPicFront())||!StrUtil.isNotBlank(distributionUserParam.getIdentityCardPicHold())){
                throw new MaoshiShopBindException("申请填写信息不全,需要身份证照片");
            }
        }
        if(distributionAuditingInfoVO.getRealName()){
            if(!StrUtil.isNotBlank(distributionUserParam.getRealName())){
                throw new MaoshiShopBindException("申请填写信息不全,需要真实姓名");
            }
        }
        MaoshiUser user = SecurityUtils.getUser();
        String userId = user.getUserId();

        DistributionUser distributionUser = distributionUserService.getByUserIdAndShopId(userId, shopId);

        if (distributionUser != null) {
            if (distributionUser.getState() == 0) {
                throw new MaoshiShopBindException("你已经提交过审核了,请耐心等待");
            }else if(distributionUser.getState() == -1){
                throw new MaoshiShopBindException("封禁中不可申请,请联系管理员");
            }else if(distributionUser.getState() == 2){
                throw new MaoshiShopBindException("已清退不可申请,请联系管理员");
            }else if (distributionUser.getState() == 1) {
                throw new MaoshiShopBindException("你的审核已经通过,无需再次审核");
            }
        }


        distributionUser = new DistributionUser();



        if (StrUtil.isNotBlank(distributionUserParam.getSharerCardNo())) {
            DistributionUser parentUser = distributionUserService.getByCardNo(distributionUserParam.getSharerCardNo());
            if (parentUser == null) {
                throw new MaoshiShopBindException("无法获取邀请人信息");
            }
            if (!Objects.equals(parentUser.getShopId(),shopId)) {
                throw new MaoshiShopBindException("邀请人店铺信息有误");
            }
            if (Objects.equals(parentUser.getUserId(), userId)) {
                throw new MaoshiShopBindException("自己无法邀请自己");
            }

            //设置上级id
            distributionUser.setParentId(parentUser.getDistributionUserId());


            //设置上级ids
            if (parentUser.getParentId() == null) {
                distributionUser.setParentIds(StringUtils.join(StrUtil.COMMA, parentUser.getDistributionUserId(), StrUtil.COMMA));
            } else {
                distributionUser.setParentIds(StringUtils.join(parentUser.getParentIds(), parentUser.getDistributionUserId(), StrUtil.COMMA));
            }

            distributionUser.setGrade(parentUser.getGrade() + 1);
        } else {
            distributionUser.setGrade(0);
        }



        if (distributionAuditingSet.getAutoCheck() == 1) {
            //判断是否需要购买置指定商品
            if (CollectionUtil.isNotEmpty(distributionAuditingSet.getAuditingConditions().getProdList()) ) {
                for (Long prodId: distributionAuditingSet.getAuditingConditions().getProdList()) {
                    // 判断有没有没有购买过指定商品
                    if (orderMapper.hasBuySuccessProd(prodId,distributionUser.getUserId()) == 0) {
                        throw new MaoshiShopBindException("不符合申请条件，请联系客服进行申请");
                    }
                }
            }

            UserShoppingDataDto userShoppingDataDto = orderMapper.calculateUserInShopData(shopId, userId);

            //判断是否需要消费金额条件
            if (distributionAuditingSet.getAuditingConditions().getExpenseAmount() != null) {
                if (userShoppingDataDto.getSumOfConsumption() == null) {
                    userShoppingDataDto.setSumOfConsumption(0.0);
                }
                if (userShoppingDataDto.getSumOfConsumption() < distributionAuditingSet.getAuditingConditions().getExpenseAmount()) {
                    throw new MaoshiShopBindException("消费金额不符合要求");
                }
            }
            //判断是否需要达到消费笔数条件
            if (distributionAuditingSet.getAuditingConditions().getExpenseNumber() != null) {
                if (userShoppingDataDto.getExpenseNumber() < distributionAuditingSet.getAuditingConditions().getExpenseNumber()) {
                    throw new MaoshiShopBindException("消费笔数不符合要求");
                }
            }
            //判断是否关注公众号
//            if (distributionAuditingSet.getAuditingConditions().getIsFocus()) {
//                AppConnect appConnect = appConnectService.getByBizUserId(user.getBizUserId(), App.MP);
//
//                if (appConnect == null) {
//                    throw new MaoshiShopBindException("请先关注公众号");
//                }
//            }
            distributionUser.setState(1);
            distributionUser.setBindTime(new Date());
        } else {
            // 待审核
            distributionUser.setState(0);
        }

        //设置信息
        distributionUser.setUserMobile(distributionUserParam.getUserMobile());
        distributionUser.setUserId(userId);
        distributionUser.setRealName(distributionUserParam.getRealName());
        distributionUser.setIdentityCardNumber(distributionUserParam.getIdentityCardNumber());
        distributionUser.setIdentityCardPicFront(distributionUserParam.getIdentityCardPicFront());
        distributionUser.setIdentityCardPicHold(distributionUserParam.getIdentityCardPicHold());
        distributionUser.setIdentityCardPicBack(distributionUserParam.getIdentityCardPicBack());
        distributionUser.setShopId(shopId);

        // level从1开始
        distributionUser.setLevel(1);
        //设置用户信息字段
        distributionUser.setNickName(user.getName());
        distributionUser.setPic(user.getPic());
        // 设置用户卡号
        distributionUser.setCardNo(idUtil.nextShortId());


        distributionUserService.registerDistributionUser(distributionUser);

        // 清除缓存
        distributionUserService.removeCacheByUserIdAndShopId(distributionUser.getUserId(),distributionUser.getShopId());
        distributionUserService.removeCacheByCardNo(distributionUser.getCardNo());
        return ResponseEntity.ok(distributionUser.getState());
    }

}
